﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract;
using Common.Contract.Authentication.Request;
using Common.Contract.SystemConfig.Request;
using Common.Service.Command;
using Common.Util;
using System;

namespace Authentication.ServiceCommand
{
    public class UpdateApplicationErrorCommand : ProviderServiceCommand<IProviderFactory, UpdateApplicationErrorRequest, ResponseRecord>
    {
        public UpdateApplicationErrorCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(UpdateApplicationErrorRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.Record == null)
            {
                throw new ArgumentException("Record must be set", "request");
            }
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            var record = Request.Record;
            var appError = new ApplicationError
            {
                Line = record.Line,
                Msg = record.Message,
                Name = record.Name,
                CreateTime = record.CreationDate,
                SoTransferFlag = record.TransferFlag.HasValue? record.TransferFlag.Value.ToBooleanString():null, 
            };
             
            try
            {
                bool savedUser = Providers.Configurations.UpdateAppError(appError);
                response.IsSuccess = savedUser;
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                response.IsSuccess = false;
            }
            return response.IsSuccess;
        }
    }
}
